<?php

class Currencies {
	/**
	 * Db Object
	 * @access		private
	 * @var			object
	 */
	var $anydb;
	
	/**
	 * error handler
	 * @access		private
	 * @var 		object
	 */
	var $error;
	
	/**
	 * current currency
	 * @access		public
	 * @var 		string
	 */
	var $currency;
	
	/**
	 * currencies data array
	 * @access		private
	 * @var 		array
	 */
	var $currencies;
	
	function Currencies ($db, $currency = 'USD') {
		// Initialize error handler
		$this->error = new Error();
		
		if (empty($db)) {
			$this->error->addError(1, 'Currencies requires anydb handler to be passed', FATAL_ERROR, true);
		}
		
		$this->anydb = $db;
		// set currency
		$this->setCurrency($currency);
		// get currencies from db
		$this->getCurrenciesFromDb();
	}
	
	function getCurrenciesFromDb () {
		$row = array();
		
		$query = <<<echo
SELECT curr as curr, usd as USD, gbp as GBP, bgn as BGN, eur as EUR, aud as AUD, cad as CAD FROM currency
echo;
		// execute query
		$this->anydb->query($query);
		// check for errors
		if (!empty($this->anydb->error)) {
			return FALSE;
		}
		
		while ($row = $this->anydb->getNext()) {
			$this->currencies[strtoupper($row['curr'])] = array_change_key_case($row, CASE_UPPER);
		}
		
		return TRUE;
	}
	
	function setCurrency ($currency) {
		if (empty($currency)) {
			return FALSE;
		}
		
		$currency = strtoupper($currency);
		
		$this->currency = $currency;
		return TRUE;
	}
	
	function getExchangeRateTo ($currency = 'USD') {
		if (empty($currency)) {
			return FALSE;
		}
		
		$currency = strtoupper($currency);
		
		return $this->currencies[$this->currency][$currency];
	}
	
	function convertTo ($amount, $currency = 'USD') {
		if (empty($currency)) {
			return FALSE;
		}
		
		$currency = strtoupper($currency);
		
		return $amount * $this->currencies[$this->currency][$currency];
	}
}
?>